import defService from '../services/dataDef';
import {message} from 'antd';
import {EDIT_TYPE_MAP} from "@/pages/DataDef/constants";
import {globeCfg} from "@/common/utils";

export default {
  state: {
    pageLoading: false,
    drawerType: EDIT_TYPE_MAP.ADD,
    drawerVisible: false,
    dataList: [],
    page: 1,
    pageSize: globeCfg.defaultPageSize,
    filter: {
      searchText: '',
      areaCode: '',
    },
    total: 0,
    selectRec: {
      uid: '',
      code: '',
      name: '',
      auditFlag: 0,
    },
  },
  reducers: {
    update(prevState, payload) {
      return {...prevState, ...payload};
    },
    showDefDrawer(prevState, type = EDIT_TYPE_MAP.ADD) {
      return {...prevState, drawerVisible: true, drawerType: type};
    },
    closeDefDrawer(prevState) {
      return {...prevState, drawerVisible: false, drawerType: EDIT_TYPE_MAP.ADD};
    },
    updateFilter(prevState, filter) {
      return {...prevState, filter: Object.assign({}, prevState.filter, filter)};
    },
    setSelected(prevState, rec) {
      return {...prevState, selectRec: rec};
    },
  },
  effects: (dispatch) => ({
    // 数据定义
    async getDefPage(payload, rootState) {
      this.setState({pageLoading: true});
      const state = rootState.def;
      const res = await defService.getDefPage(state.page, state.pageSize, state.filter);
      const pr = res.data; // 分页数据
      this.setState({dataList: pr.list, total: pr.totalRow, pageLoading: false});
    },
    async onSearch() {
      await dispatch.def.getDefPage();
    },
    async onPageChange({page, pageSize}) {
      this.setState({page: page, pageSize: pageSize});
      await dispatch.def.getDefPage();
    },
    async addDefInfo(defInfo) {
      const res = await defService.addDefInfo(defInfo);
      if (res.code > 0) {
        message.info('保存成功');
        this.setState({drawerVisible: false});
        await dispatch.def.getDefPage();
      }
    },
    async updateDefInfo(defInfo, rootState) {
      const res = await defService.updateDefInfo(defInfo);
      if (res.data.code > 0) {
        message.info('保存成功');
        await dispatch.def.getDefPage();
      }
    },
    async deleteDefInfo(defInfo) {
      const res = await defService.deleteDefInfo(defInfo.uid);
      if (res.data.code > 0) {
        message.info('删除成功');
        await dispatch.def.getDefPage();
      }
    },
  }),
};
